/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.starmeep.client;


import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dev.util.msg.Message0;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtext.client.core.Connection;

import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.data.*;
import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.Viewport;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.*;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.form.event.FormListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridRowListener;
import com.gwtext.client.widgets.layout.AnchorLayoutData;
import com.gwtext.client.widgets.layout.ColumnLayout;
import com.gwtext.client.widgets.layout.ColumnLayoutData;
import com.gwtext.client.widgets.layout.FormLayout;
import com.gwtext.client.widgets.layout.HorizontalLayout;
import com.gwtext.client.widgets.layout.VerticalLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;



/**
 * Main entry point.
 *
 * @author CARLOS
 */
public class MainEntryPoint implements EntryPoint {


    Store store;
    FormPanel formPanel,formCreateJob;
    TabPanel tabPanel;
    Panel panelTabRun=new Panel(),panelTabConfig=new Panel();
    Button btCreateJob,btShowFiles,btViewHost,btEnterCommand,btRunStopJob,btCheckJob,btDeleteJob,btFinalizeConf,btUploadConf;
    TextField txtCommands;
    ComboBox cbJobs;
    com.google.gwt.user.client.ui.Button btStartupCluster;
    int numberNodesavailable;
    Map jobs= new HashMap(),configCluster;
    ArrayList<String> namesJobs=new ArrayList();
    ArrayList<Map> filesJob=new ArrayList();
    //Cajas Label y cajas de texto para la seccion de cuenta en AWS
    TextField awsKey = new TextField("AWS KEY", "awsKey");
    TextField secretAws = new TextField("Secret AWS", "secretAws");
    TextField accountNumber = new TextField("Account Number", "accountNumber");
    //Creacion de las Cajas de texto y labels para requerir informacion acerca del cluster
    TextField clusterName = new TextField("Cluster Name", "clusterName");
    TextField keyName = new TextField("Key Name", "keyName");
    TextField keyLocation  = new TextField("Key Location", "keyLocation");
     //Creacion de cajas de texto y label donde el usuario ingresa información acerca del EBS
    TextField ebsVolumeId = new TextField("Volume ID", "ebsVolumeId");
    TextField ebsDevice  = new TextField("Device", "ebsDevice");
    TextField ebsPartition = new TextField("Partition", "ebsPartition");
    TextField ebsMountPath  = new TextField("Mount Path", "ebsMountPath");

     //Creacion de cajas de texto y label donde el usuario escoge un archivo de configuracion
    TextField flFileLoad  = new TextField("Upload Configuration", "flFileLoad");
     //ComboBox para elegir el número de nodos que se levantarán
    ComboBox clusterSize = new ComboBox();
     //Creacion de Combobox para el fieldset de Cluster Information
    ComboBox clusterShell = new ComboBox();
    ComboBox clusterZone = new ComboBox();
    GridPanel grid;
    RecordDef recordDef;
    Store storeGridJobs;
    AsyncCallback<ArrayList<Map>> callbackShowFiles;
    
    /**
     * Creates a new instance of MainEntryPoint
     */
    public MainEntryPoint() {
        /*******************************************
         *DECLARACIONES DE LOS ELEMENTOS A UTILIZAR*
         *******************************************/
         //Panel donde se agrega todo los componentes para ser agregado al root document
         Panel panel = new Panel();
         //Creacion de los Tab Panels que se encarga de mostrar los diferentes paneles en forma de TABS
         tabPanel = new TabPanel();
         //Creacion del Form Panel Principal que actua como form HTML que contendrá todos los elementos y sus valores al momento de realizar una acción
         formPanel = new FormPanel();
         /**********************************************************
          * FIN DECLARACIONES DE COMPONENTES A UTILIZARSE***********
          **********************************************************/

         /*********************************************************
          * DISEÑO DE LA PARTE GRAFICA DEL PROYECTO*****************
          *********************************************************/
         //Modificando características del Panel
         panel.setBorder(false);
         panel.setPaddings(15);
         //Modificando características del Tab Panel
         tabPanel.setBorder(false);
         //Modificando características del Formulario através de la función init form
         initForm(formPanel);
         //Creando los paneles para la configuración del Cluster
         create_Panel_Configuration();
         //Creando los paneles para la ejecución del Cluster
         create_Panel_Launch();
         //Agregando los paneles como tabs
         tabPanel.add(panelTabConfig);
         tabPanel.add(panelTabRun);
         
         //Formulario que contendrá los valores de todos los componentes contenidos
         formPanel.add(tabPanel);
         
         Panel pnBanner=new Panel();
         Panel pnBannerImage=new Panel();
         Image widget = new Image("images/logo.png");
         pnBannerImage.add(widget);
         //p.set
         pnBannerImage.setStyle("position:relative;left:50%;margin-left:-200px;");
         pnBanner.add(pnBannerImage);
         pnBannerImage.setBodyStyle("background-color:F1F1F1");
         pnBannerImage.setBorder(false);
         pnBanner.setWidth("50%");
         pnBanner.setBodyStyle("background-color:F1F1F1");
         panel.add(pnBanner);

         panel.add(formPanel);
        
        
         panel.addClass("CenterPanel");

        final AsyncCallback<Map> callIsRunningConfig = new AsyncCallback<Map>() {
            public void onSuccess(Map result) {
               if(result!=null)
               {
                   configCluster=result;
                   numberNodesavailable=Integer.parseInt((String)configCluster.get("cbSizeTotal"));
                   
                   setFieldConfiguration(configCluster);
                    if(((String)result.get("isClusterRun")).equals("1"))
                    {
                       tabPanel.setActiveTab(1);
                       btStartupCluster.setText("Stop Cluster");
                       btCreateJob.enable();
                       cbJobs.enable();
                     }
               }
            }
             public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
        };
         getService().isClusterRunning(callIsRunningConfig);
         RootPanel.get().add(panel);
         
    }

    /**
     * The entry point method, called automatically by loading a module
     * that declares an implementing class as an entry-point
     */
    public void onModuleLoad() {

    }
      public static GWTServiceAsync getService() {
        // Create the client proxy. Note that although you are creating the
        // service interface proper, you cast the result to the asynchronous
        // version of the interface. The cast is always safe because the
        // generated proxy implements the asynchronous interface automatically.

        return GWT.create(GWTService.class);
    }
    /**FUNCION QUE PERMITE OBTENER LOS VALORES DE LOS COMPONENTES CONTENIDOS
     * EN UN FORMULARIO
     * @param form
     * @return Map
     */
    private Map getDataForm( Form form )
    {
      String formValues = form.getValues();
      Map loginData = new HashMap();
      String[] nameValuePairs = formValues.split( "&" );
      for (int i = 0; i < nameValuePairs.length; i++) {
         String[] oneItem = nameValuePairs[i].split( "=" );
         if(oneItem.length>1)
            loginData.put( oneItem[0], oneItem[1] );
         else
             loginData.put( oneItem[0], "" );
      }
      return loginData;
    }
    /***FUNCION QUE PERMITE EL DISEÑO DEL PANEL
     * DE CONFIGURACIÓN DE STARMEEP
     */
    private void create_Panel_Configuration()
    {
         //Creacion del Fieldset para cada sección definida en el Proyecto
         FieldSet detailsFS = new FieldSet("AWS Information");
         FieldSet clusterDefinition = new FieldSet("Cluster");
         FieldSet ebsDefinition = new FieldSet("EBS VOLUME (OPTIONAL)");
         FieldSet fsLoadConfiguration = new FieldSet("LOAD CONFIGURATION (OPTIONAL)");


         //Creacion de paneles para dividir cada seccion en varias columnas dependiendo el numero de columnas.
         Panel columnOnePanel = new Panel();
         Panel columnTwoPanel = new Panel();
         Panel columnTreePanel = new Panel();
         //Creacion de las tres columnas para dividir el Fieldset de informacion de Cluster
         Panel columnOne = new Panel();
         Panel columnTwo = new Panel();
         Panel columnThree = new Panel();
         //Creacion de las tres columnas para dividir el Fieldset de EBS-VOLUME
         Panel oneColumn = new Panel();
         Panel twoColumn = new Panel();
         Panel threeColumn = new Panel();
         Panel fourColumn = new Panel();

         //Panel que contiene el boton de submit para configurar starcluster
         Panel panelAddClusterButton= new Panel();

         //ComboBox para elegir el número de nodos que se levantarán
         Store optionSize=comboBoxNumber(20);
  
         //Creacion de Combobox para el fieldset de Cluster Information
         final Store optionShell = new SimpleStore(new String[]{"types"},  new String[][]{new String[]{"bash"},new String[]{"zsh"},new String[]{"csh"},new String[]{"ksh"},new String[]{"tsch"}});
         final Store optionZone = new SimpleStore(new String[]{"types"},  new String[][]{new String[]{"us-east-1a"},new String[]{"us-east-1b"},new String[]{"us-east-1c"},new String[]{"us-east-1d"}});

         initTabConfig(panelTabConfig,"Configuration","F1F1F1");
         initTabConfig(panelTabRun,"Run Cluster","F1F1F1");
        
         //Creacion de paneles para dividir en tres columnas la informacion a pe    dir en la seccion AWS
         columnOnePanel.setLayout(new FormLayout());
         columnOnePanel.add(awsKey, new AnchorLayoutData("85%"));
         columnTwoPanel.setLayout(new FormLayout());
         columnTwoPanel.add(secretAws, new AnchorLayoutData("85%"));
         columnTreePanel.setLayout(new FormLayout());
         columnTreePanel.add(accountNumber, new AnchorLayoutData("85%"));

         //Agregar las columnas al FieldSet
         detailsFS.setLayout(new ColumnLayout());
         detailsFS.add(columnOnePanel, new ColumnLayoutData(0.3333333));
         detailsFS.add(columnTwoPanel, new ColumnLayoutData(0.3333333));
         detailsFS.add(columnTreePanel, new ColumnLayoutData(0.3333333));
         panelTabConfig.add(detailsFS);

          //Creacion del Fieldset para la seccion de Cluster
         clusterDefinition.setLayout(new ColumnLayout());
         
         optionSize.load();
         initComboBox(clusterSize, optionSize,"cbSizeTotal", "Size", "Choose a number","Searching...", "1");

         //Funcion que indica que el input es de tipo file.
         keyLocation.setInputType("file");
         //Creacion de los Combobox.
         optionShell.load();
         initComboBox(clusterShell, optionShell,"cbShell", "Shell", "Enter shell","Searching...", "bash");

         optionZone.load();
         initComboBox(clusterZone, optionZone,"cbZone", "Zone", "Enter Zone","Searching...", "us-east-1a");

         //Creacion de las tres columnas para dividir el Fieldset de informacion de Cluster
         columnOne.setLayout(new FormLayout());
         columnTwo.setLayout(new FormLayout());
         columnThree.setLayout(new FormLayout());

         //Agregar los elementos creados anteriormente a las columnas
         columnOne.add(clusterZone,new AnchorLayoutData("85%"));
         columnTwo.add(clusterShell, new AnchorLayoutData("85%"));
         columnOne.add(keyName,new AnchorLayoutData("85%"));
         columnTwo.add(keyLocation,new AnchorLayoutData("85%"));
         columnThree.add(clusterSize, new AnchorLayoutData("85%"));

         //Agregar y definicion del ancho que ocupara las columnas en el FieldSet de información del Cluster
         clusterDefinition.add(columnOne, new ColumnLayoutData(0.3333333));
         clusterDefinition.add(columnTwo, new ColumnLayoutData(0.3333333));
         clusterDefinition.add(columnThree, new ColumnLayoutData(0.3333333));

         //Agregar la seccion de Definicion de Cluster al formulario principal
        panelTabConfig.add(clusterDefinition);
         //Creacion de un FieldSet para la seccion que define un Volumen EBS
        ebsDefinition.setCollapsible(true);
        ebsDefinition.setLayout(new ColumnLayout());
        //Creación de Paneles que dividen la Sección de EBS en cuatro columnas.
        oneColumn.setLayout(new FormLayout());
        twoColumn.setLayout(new FormLayout());
        threeColumn.setLayout(new FormLayout());
        fourColumn.setLayout(new FormLayout());

        //Creacion del Panel donde agregaremos el Boton de Agregar Fila
        panelAddClusterButton.setBorder(false);
        //Validaciones
        awsKey.setAllowBlank(false);
        awsKey.setRegex("^[0-9a-zA-Z]*$");
        awsKey.setRegexText("The format is incorrected, Must have only number and letters");
        secretAws.setInputType("password");
        secretAws.setAllowBlank(false);
        accountNumber.setAllowBlank(false);
        accountNumber.setRegex("^([0-9]*\\-{1}[0-9]*)*[0-9]$");
        clusterName.setAllowBlank(false);
        clusterName.setRegex("^[a-zA-Z]*$");
        clusterName.setRegexText("Only Characters is allowed");
        keyName.setAllowBlank(false);
        keyName.setRegex("^[a-zA-Z\\-]*$");
        keyLocation.setAllowBlank(false);
        ebsVolumeId.setAllowBlank(true);
        ebsVolumeId.setRegex("^[0-9a-zA-Z]*\\-{1}[0-9a-zA-Z]*$");
        ebsVolumeId.setRegexText("The format is incorrected, example: vol-a7ts648o");
        ebsDevice.setAllowBlank(true);
        ebsDevice.setRegex("^/{1}[a-zA-Z]*/{1}[a-zA-Z]*$");
        ebsDevice.setRegexText("The format is incorrected, example: /dev/sdj");
        ebsPartition.setAllowBlank(true);
        ebsPartition.setRegex("^[0-9]*$");
        ebsPartition.setRegexText("Only Numbers is allowed");
        ebsMountPath.setAllowBlank(true);
        ebsMountPath.setRegex("^(/{1}[a-zA-Z])*");
        ebsMountPath.setRegexText("The format is incorrected, example: /home");

        final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
            public void onSuccess(Boolean result) {
                System.out.print("VAlor de Creacion del archivo conf:"+result);
                if(!result.booleanValue())
                {
                    MessageBox.alert("Error the creation de file config");
                    configCluster=null;
                }
                else{

                    MessageBox.alert("The creation file has been created successfully");
                    tabPanel.setActiveTab(1);
                    numberNodesavailable=Integer.parseInt((String)configCluster.get("cbSizeTotal"));
                }
            }
            public void onFailure(Throwable caught) {
            }
        };

        btFinalizeConf = new Button("Finalize Configuration", new ButtonListenerAdapter() {
            @Override
             public void onClick(Button button, EventObject e) {
                 if(formPanel.getForm().isValid())
                     if(!ebsDevice.getText().equals("")||!ebsMountPath.getText().equals("")||!ebsPartition.getText().equals("")||!ebsVolumeId.getText().equals("") )
                     {
                         if(!ebsDevice.getText().equals("")&&!ebsMountPath.getText().equals("")&&!ebsPartition.getText().equals("")&&!ebsVolumeId.getText().equals(""))
                            formPanel.getForm ().submit("GWTUpLoadFile?op=fileCONF", null, Connection.POST,"Saving Data...", false);
                         else
                             MessageBox.alert("Please complete all information about EBS Volume");
                     }
                     else
                        formPanel.getForm ().submit("GWTUpLoadFile?op=fileCONF", null, Connection.POST,"Saving Data...", false);
                 else
                     MessageBox.alert("Error, complete the information");
             }
         });
         btFinalizeConf.setIconCls("finalize-configuration-icon");
         btFinalizeConf.setStyle("position:relative;left:50%;margin-left:-80px;");

         
         btUploadConf = new Button("Upload Config", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e) {
                  if(!flFileLoad.getText().equals(""))
                     formPanel.getForm ().submit("GWTUpLoadFile?op=fileUploadCONF", null, Connection.POST,"Loading Data...", false);
                 else
                     MessageBox.alert("You must choose a file config");
             }
         });
         btUploadConf.setIconCls("upload-job-icon");


         final AsyncCallback<Map> callbackLoadConfiguration = new AsyncCallback<Map>() {
            public void onSuccess(Map result) {
                System.out.print("Entrada set Load Configuration");
               if(result!=null)
                   setFieldConfiguration(result);
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
          };

         formPanel.addFormListener(new FormListenerAdapter(){
            public boolean doBeforeAction(Form form) {return true;}
            public void onActionComplete(Form form, int httpStatus, java.lang.String responseText){
 
                if(responseText.compareTo("File Key Location upload is failed")==0)
                    MessageBox.alert(responseText);
                else if(responseText.contains("fileUploadCONF"))
                {
                    System.out.println(responseText);
                    getService().loadConfiguration(callbackLoadConfiguration);
                }
                else
                {
                    System.out.print("entrada finalizar");
                    configCluster=getDataForm(formPanel.getForm());
                    responseText=responseText.replaceAll("<pre>", "");
                    responseText=responseText.replaceAll("</pre>", "");
                    System.out.print("mitad finalizar");
                    configCluster.put("keyLocation", responseText);
                    getService().finalizaConfiguration(configCluster, callback);
                }
            }
            @Override
            public void onActionFailed(Form form, int httpStatus, java.lang.String responseText){
            com.google.gwt.user.client.Window.alert("File upload is failed.");
            }
         });
        panelAddClusterButton.add(btFinalizeConf);
        //Agregar los respectivos elementos acerca de la información a requerir del EBS a los paneles columnas.
        oneColumn.add(ebsVolumeId, new AnchorLayoutData("85%"));
        twoColumn.add(ebsDevice, new AnchorLayoutData("85%"));
        threeColumn.add(ebsPartition, new AnchorLayoutData("85%"));
        fourColumn.add(ebsMountPath, new AnchorLayoutData("85%"));

        //Agregar las columnas al panel principal.
        ebsDefinition.add(oneColumn,new ColumnLayoutData(0.25));
        ebsDefinition.add(twoColumn,new ColumnLayoutData(0.25));
        ebsDefinition.add(threeColumn,new ColumnLayoutData(0.25));
        ebsDefinition.add(fourColumn,new ColumnLayoutData(0.25));
        //Agregar la seccion EBS al formulario.
        panelTabConfig.add(ebsDefinition);
        
        fsLoadConfiguration.setLayout(new FormLayout());
        fsLoadConfiguration.setCollapsible(true);
        fsLoadConfiguration.setCollapsed(true);
        flFileLoad.setInputType("file");

        oneColumn=new Panel();
        twoColumn=new Panel();
        oneColumn.setLayout(new HorizontalLayout(10));
        twoColumn.setLayout(new FormLayout());
        twoColumn.setPaddings(5,0,0,0);

        twoColumn.add(flFileLoad);
        oneColumn.add(twoColumn);
        btUploadConf.setStyle("position:relative;margin-top:12px;");
        oneColumn.add(btUploadConf);
        oneColumn.setPaddings(5);
        fsLoadConfiguration.add(oneColumn);

        panelTabConfig.add(fsLoadConfiguration);
        //Boton para Finalizar Cofiguracion
        panelTabConfig.add(panelAddClusterButton);

    }
    private void create_Panel_Launch()
    {    
         btStartupCluster=new com.google.gwt.user.client.ui.Button("Launch Cluster");
         btStartupCluster.setHeight("30px");
         btStartupCluster.setWidth("200px");
         FieldSet fsMenu=new FieldSet();
         fsMenu.setPaddings(36,10,20, 36);
         Panel panelBody=new Panel();
         Panel panelJob=new Panel();
         fsMenu.setBorder(true);
         panelBody.setBorder(true);
         Panel firstColumn=new Panel();
         Panel secondColumn=new Panel();
         FieldSet fsRunCluster = new FieldSet("Run Cluster");
         fsRunCluster.setPaddings(5,10,10,5);
         Panel panelRunCluster=new Panel();  
         FieldSet fsJob = new FieldSet();
         fsJob.setPaddings(5);

         final AsyncCallback<String> callbackLaunch = new AsyncCallback<String>() {
            public void onSuccess(String result) {
               if(!result.contains("error"))
               {
                  if(result.contains("stopping"))
                  {
                        result=result.replaceAll("stopping", "");
                        jobs=new HashMap();
                        namesJobs=new ArrayList<String>();
                        btStartupCluster.setText("Launch Cluster");
                        btFinalizeConf.enable();
                        btUploadConf.enable();
                        disableComponentsLaunchCluster();
                        Store init=createStoreInit();
                        cbJobs.setStore(init);
                        cbJobs.setValue("Jobs");
                      //  if(result.equals("")||result.equals(" "))
                            MessageBox.alert("You cluster has been stopping...");
                  }
                  else
                  {
                        result=result.replaceAll("starting", "");
                        btStartupCluster.setText("Stop Cluster");
                        btCreateJob.enable();
                        btFinalizeConf.disable();
                        btUploadConf.disable();
                        cbJobs.enable();
                     //   if(result.equals("")||result.equals(" "))
                            MessageBox.alert("Finally!!! your cluster is running!");
                  }
                  


                  
               }
               else
                   MessageBox.alert(result);
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication Failed");
            }
          };
         btStartupCluster.addClickHandler(new ClickHandler(){
            public void onClick(ClickEvent event) {
                final Map config=getDataForm(formPanel.getForm());
                  if(!btStartupCluster.getText().contains("Launch Cluster"))
                  {
                      MessageBox.confirm("Confirm", "Are you sure you want to do that?",
                             new MessageBox.ConfirmCallback() {
                                 public void execute(String btnID) {
                                        if(btnID.equals("yes"))
                                        {
                                            com.gwtext.client.widgets.MessageBox.wait("Please wait (And make yourself a cup of coffee)");
                                            getService().launchCluster(config, callbackLaunch);
                                        }
                                 }
                             });
                  }
                  else{
                       com.gwtext.client.widgets.MessageBox.wait("Please wait (And make yourself a cup of coffee)");
                       getService().launchCluster(config, callbackLaunch);
                  }

            }
        });
         btCreateJob = new Button("Create Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", new ButtonListenerAdapter() {
            @Override
             public void onClick(Button button, EventObject e) {
                 final Window window = new Window();
                 formCreateJob=new FormPanel();
                 initForm(formCreateJob);
                 formCreateJob.setWidth("100%");
                 TextField txtNameJob = new TextField("Job", "txtNameJob");
                 TextField fileCtl = new TextField("CTL file", "fileCtl");
                 TextField txtParams = new TextField("Parameters", "txtParams");
                 txtNameJob.setRegex("^[A-Za-z]*$");
                 txtNameJob.setAllowBlank(false);
                 fileCtl.setAllowBlank(false);
                 fileCtl.setRegex("^[a-zA-Z]*.ctl$");
                 fileCtl.setRegexText("Error: The file must be the extension .ctl");
                 txtParams.setWidth("550px");
                 fileCtl.setInputType("file");
                 final ComboBox cbNodos= new ComboBox();
                 com.google.gwt.user.client.ui.Button btUpJob=new com.google.gwt.user.client.ui.Button("Create Job");
                 btUpJob.setSize("100px","30px");
                 btUpJob.addClickHandler(new ClickHandler(){
                 public void onClick(ClickEvent event) {
                       if(formCreateJob.getForm().isValid())
                      {
                          Map mpCreateJob=getDataForm(formCreateJob.getForm());
                          if (mpCreateJob.get("cbSize").equals("0"))
                              MessageBox.alert("Error, You must choose more than 0 of size");
                          mpCreateJob.put("id","-1");
                          String nameJob=(String)mpCreateJob.get("txtNameJob");
                          String param=(String)mpCreateJob.get("txtParams");
                          String size=(String)mpCreateJob.get("cbSize");
                          formCreateJob.getForm().submit("GWTUpLoadFile?op=fileCTL&nameJob="+nameJob+"&param="+param+"&size="+size,null, Connection.POST,"Creating JOB...", false);

                      }
                      else
                         MessageBox.alert("Error, complete the information");
                    }
                });
                
                 
                 formCreateJob.addFormListener(new FormListenerAdapter(){
                 public boolean doBeforeAction(Form form) {return true;}
                 public void onActionComplete(Form form, int httpStatus, java.lang.String responseText){
                    if(responseText!=null && !responseText.equals(""))
                    {
                        Map mpCreateJob=getDataForm(formCreateJob.getForm());
                        namesJobs.add( (String)mpCreateJob.get("txtNameJob"));
                        
                        Store stCbJobs=createStore(namesJobs);
                        responseText=responseText.replaceAll("<pre>", "");
                        responseText=responseText.replaceAll("</pre>", "");
                        mpCreateJob.put("ctlName", responseText);
                        mpCreateJob.put("isRunning", false);
                        numberNodesavailable=numberNodesavailable-Integer.parseInt((String)mpCreateJob.get("cbSize"));
                        jobs.put((String)mpCreateJob.get("txtNameJob"),mpCreateJob);
                        stCbJobs.reload();
                        cbJobs.setValue((String)mpCreateJob.get("txtNameJob"));
                        cbJobs.setStore(stCbJobs);
                        MessageBox.alert("The Creation Job is Successfullfy");
                        btDeleteJob.enable();
                        btCheckJob.disable();
                        btShowFiles.disable();
                        btRunStopJob.enable();
                        btRunStopJob.setText("Run Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp");
                        btRunStopJob.setIconCls("run-job-icon");
                        window.close();
                    }
                    else
                        MessageBox.alert("Error in creation the job");
                 }
                 public void onActionFailed(Form form, int httpStatus, java.lang.String responseText){
                        MessageBox.alert("File Upload is failed.");
                    }
                 });
                 Store cbStoreNodos=comboBoxNumber(numberNodesavailable);
                 cbStoreNodos.load();
                 initComboBox(cbNodos,cbStoreNodos,"cbSize", "Choose a number", "0","Loading...", "");
                 Panel pnCbFiles=new Panel();
                 pnCbFiles.setLayout(new FormLayout());
                 pnCbFiles.setBodyStyle("background-color:F1F1F1");
                 pnCbFiles.add(cbNodos);
                 Panel pnCreateJobFile1=new Panel();
                 Panel pnCreateJob=new Panel();
                 Panel pnFormLayout=new Panel();     
                 pnCreateJobFile1.setLayout(new HorizontalLayout(5));
                 pnCreateJob.setLayout(new VerticalLayout(5));
                 pnFormLayout.setLayout(new FormLayout());
                 pnFormLayout.setWidth(175);
                 pnFormLayout.add(txtNameJob);
                 pnCreateJobFile1.add(pnFormLayout);
                 pnFormLayout=new Panel();
                 pnFormLayout.setLayout(new FormLayout());
                 pnFormLayout.setWidth(225);
                 pnFormLayout.add(cbNodos);
                 pnCreateJobFile1.add(pnFormLayout);
                 pnFormLayout=new Panel();
                 pnFormLayout.setLayout(new FormLayout());
                 pnFormLayout.setWidth(250);
                 pnFormLayout.add(fileCtl);
                 pnCreateJobFile1.add(pnFormLayout);

                 pnCreateJob.add(pnCreateJobFile1);

                 pnCreateJobFile1=new Panel();
                 pnCreateJobFile1.setLayout(new HorizontalLayout(5));
                 pnFormLayout=new Panel();
                 pnFormLayout.setLayout(new FormLayout());
                 pnFormLayout.setWidth(575);
                 pnFormLayout.add(txtParams);
                 pnCreateJobFile1.add(pnFormLayout);

                 pnCreateJob.add(pnCreateJobFile1);

                 pnFormLayout=new Panel();
                 pnFormLayout.setPaddings(0,250,0,0);
                 pnFormLayout.add(btUpJob);
                 pnCreateJob.add(pnFormLayout);
                 
                 formCreateJob.add(pnCreateJob);
                 window.setClosable(true);
                 window.setTitle("Create Job");
                 window.setWidth(675);
                 window.setHeight(200);
                 window.setModal(true);
                 window.add(formCreateJob);
                 window.show(button.getId());
             }
         });
         btCreateJob.setIconCls("create-job-icon");

         final AsyncCallback<String> callbackDeleteJob = new AsyncCallback<String>() {
            public void onSuccess(String result) {
               if(result!=null)
               {
                   Store stCbJobs;
                   Map job=(Map)jobs.remove(cbJobs.getText());   
                   namesJobs.remove((String)job.get("txtNameJob"));
                   numberNodesavailable=numberNodesavailable+Integer.parseInt((String)job.get("cbSize"));
                   stCbJobs= createStore(namesJobs);
                   stCbJobs.reload();
                   cbJobs.setStore(stCbJobs);
                   cbJobs.setValue("Jobs");
                   MessageBox.alert("The Job has been deleted sucessfully");
                   btDeleteJob.disable();
                   btRunStopJob.disable();
               }
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
          };
         btDeleteJob = new Button("Delete Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e)
             {
                   MessageBox.confirm("Confirm", "Are you sure you want to delete the job?",
                         new MessageBox.ConfirmCallback() {
                             public void execute(String btnID) {
                                 if(btnID.equals("yes"))
                                     getService().deleteJob(cbJobs.getText(), callbackDeleteJob);
                             }
                         });
             }
         });
         btDeleteJob.setIconCls("delete-job-icon");
         

         final AsyncCallback<String> callbackRunJob = new AsyncCallback<String>() {
            public void onSuccess(String result) {
               if(!result.contains("Error"))
               {
                   Map config=getDataForm(formPanel.getForm());
                   Map job=(Map)jobs.get((String)config.get("cbJobs"));
                   job.put("idJob",result);
                   if(result.equals("-1"))
                   {
                       job.put("isRunning", false);
                       btRunStopJob.setText("Run Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp");
                       btRunStopJob.setIconCls("run-job-icon");
                       MessageBox.alert("The job has been stopping succesfull");
                       btDeleteJob.enable();
                       btCheckJob.disable();
                       btShowFiles.disable();
                       btEnterCommand.enable();
                       btEnterCommand.disable();
                       btCreateJob.enable();
                       btRunStopJob.enable();
                       btFinalizeConf.enable();
                       btUploadConf.enable();
                   }
                   else
                   {
                       btDeleteJob.disable();
                       btCheckJob.enable();
                       btShowFiles.enable();
                       btFinalizeConf.disable();
                       btUploadConf.disable();
                       btEnterCommand.enable();

                       job.put("isRunning", true);
                       btRunStopJob.setText("Stop Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp");
                       btRunStopJob.setIconCls("stop-job-icon");
                       MessageBox.alert("The job has been starting succesfull");
                       getService().showFiles(cbJobs.getText(), callbackShowFiles);
                   }
                   btViewHost.enable();
                   jobs.put((String)config.get("cbJobs"),job);
               }
               else
                   MessageBox.alert(result);
            }
            public void onFailure(Throwable caught) {
                
            }
          };

         btRunStopJob = new Button("Run Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e) {
                 Map config=getDataForm(formPanel.getForm());
                 String jobName=(String)config.get("cbJobs");
                 getService().RunJob(jobName, callbackRunJob);

             }
         });
         btRunStopJob.setIconCls("run-job-icon");
          
         final AsyncCallback<String> callbackCheckJob = new AsyncCallback<String>() {
            public void onSuccess(String result) {
               MessageBox.alert(result);
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
          };

         btCheckJob = new Button("Check Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e) {
                 Map job=(Map)jobs.get(cbJobs.getText());
                 getService().checkJob((String)job.get("txtNameJob"), callbackCheckJob);
             }
         });
         btCheckJob.setIconCls("check-job-icon");
         


          final AsyncCallback<String> callbackHostStatus = new AsyncCallback<String>() {
            public void onSuccess(String result) {
               MessageBox.alert(result);
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
          };
         btViewHost = new Button("View Host Status", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e) {
                 Map config=getDataForm(formCreateJob.getForm());
                 getService().viewHostStatus(config, callbackHostStatus);
             }
         });
         btViewHost.setIconCls("view-host-icon");
         
         callbackShowFiles = new AsyncCallback<ArrayList<Map>>() {
            public void onSuccess(ArrayList<Map> files) {
                Object[][] data = createStoreGridJobFiles(files);
                MemoryProxy proxy = new MemoryProxy(data);
                ArrayReader reader = new ArrayReader(recordDef);
                filesJob=files;
                Store store = new Store(proxy, reader);
                store.load();
                storeGridJobs.removeAll();
                storeGridJobs.add(store.getRecords());
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
          };
         btShowFiles = new Button("Refresh Files&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e) {
                 getService().showFiles(cbJobs.getText(), callbackShowFiles);
             }
         });
         btShowFiles.setIconCls("show-files-icon");

         final AsyncCallback<String> callbackEnterCommand = new AsyncCallback<String>() {
            public void onSuccess(String result) {
               MessageBox.alert(result);
               getService().showFiles(cbJobs.getText(), callbackShowFiles);
            }
            public void onFailure(Throwable caught) {
                MessageBox.alert("Communication failed");
            }
          };
         btEnterCommand = new Button("Enter", new ButtonListenerAdapter() {
             public void onClick(Button button, EventObject e) {
                  
                 getService().enterCommand(cbJobs.getText(),txtCommands.getText(),callbackEnterCommand);
             }
         });

         cbJobs= new ComboBox();
         initComboBox(cbJobs,null,"cbJobs", "Choose a Job", "Jobs","Loading...", "");
         cbJobs.setDisplayField("types");
         cbJobs.setAllowBlank(true);
         cbJobs.setWidth(110);
         cbJobs.addListener(new ComboBoxListenerAdapter() {
             public void onSelect(ComboBox comboBox, Record record, int index) {
                 String select=cbJobs.getText();
                 if(!select.equals("Jobs") && !select.equals(""))
                 {
                    Map job=(Map)jobs.get(select);
                    if((Boolean)job.get("isRunning"))
                    {
                        btDeleteJob.disable();
                        btCheckJob.enable();
                        btShowFiles.enable();
                        btRunStopJob.setText("Stop Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                        btRunStopJob.setIconCls("stop-job-icon");
                    }
                    else
                    {
                        btDeleteJob.enable();
                        btCheckJob.disable();
                        btShowFiles.disable();
                        btRunStopJob.enable();
                        btRunStopJob.setText("Run Job&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp");
                        btRunStopJob.setIconCls("run-job-icon");
                    }
                 }
                 else
                 {
                        btCheckJob.disable();
                        btShowFiles.disable();
                        btDeleteJob.disable();
                        btRunStopJob.disable();
                 }    
             }
         });

          recordDef = new RecordDef(
                 new FieldDef[]{
                         new StringFieldDef("nameFiles"),
                         new FloatFieldDef("sizeFiles"),
                         new StringFieldDef("downloadFiles"),
                 }
         );
         Object[][] data = getCompanyData();
         MemoryProxy proxy = new MemoryProxy(data);

         ArrayReader reader = new ArrayReader(recordDef);
         storeGridJobs = new Store(proxy, reader);
         storeGridJobs.load();

         grid = new GridPanel();
         grid.setStore(storeGridJobs);

         ColumnConfig[] columns = new ColumnConfig[]{
                 new ColumnConfig("Name Files", "nameFiles",230,true,null,"nameFiles"),
                 new ColumnConfig("Size", "sizeFiles",230),
                 new ColumnConfig("Download", "downloadFiles",230)
         };

         ColumnModel columnModel = new ColumnModel(columns);
         grid.setColumnModel(columnModel);
         grid.setFrame(true);
         grid.setStripeRows(true);
         grid.setTitle("Job Files");
         grid.setHeight(255);
         grid.setWidth(740);

          grid.addGridRowListener(new GridRowListener() {
             public void onRowClick(GridPanel grid, int rowIndex, EventObject e) {
             }

             public void onRowDblClick(GridPanel grid, int rowIndex, EventObject e) {
                 Window windowDetails=new Window();
                 TextArea txtArOutput = new TextArea("Output", "txtArOutput");
                 Map fileJob=filesJob.get(rowIndex);
                 
                 txtArOutput.setHeight("230px");
                 txtArOutput.setWidth("600px");
                 txtArOutput.setValue((String)fileJob.get("lineFiles"));
                 windowDetails.setClosable(true);
                 windowDetails.setTitle("Details");
                 windowDetails.setWidth(600);
                 windowDetails.setHeight(250);
                 windowDetails.setModal(true);
                 windowDetails.add(txtArOutput);
                 windowDetails.show();
             }
             public void onRowContextMenu(GridPanel grid, int rowIndex, EventObject e) {
             }
         });

         Panel pnCommand=new Panel();
         firstColumn=new Panel();
         pnCommand.setLayout(new FormLayout());
         txtCommands=new TextField("Enter the command","txtCommands");
         pnCommand.add(txtCommands,new AnchorLayoutData("97%"));
         Panel pnBtEnterCommand=new Panel();
         pnBtEnterCommand.add(btEnterCommand);
         pnBtEnterCommand.setStyle("position:relative;left:50%;margin-right:20px;");
         pnCommand.add(pnBtEnterCommand);

         panelJob.setLayout(new FormLayout());
         panelJob.add(grid);
         panelJob.add(pnCommand);

         Label lbStartup = new Label();
         lbStartup.setText("Startup");
         
         panelRunCluster.setLayout(new HorizontalLayout(5));
         panelRunCluster.setPaddings(0,300,0,0);
         panelRunCluster.add(btStartupCluster);
         fsRunCluster.add(panelRunCluster);

         Panel panelComboJobs=new Panel();
         panelComboJobs.setLayout(new FormLayout());
         panelComboJobs.add(cbJobs);

         fsMenu.setLayout(new VerticalLayout());
         FieldSet fsMenuHost=new FieldSet("Monitoring Ganglia");
         FieldSet fsMenuJob=new FieldSet("Menu VIEWS");
         fsMenuHost.setLayout(new VerticalLayout());
         fsMenuJob.setLayout(new VerticalLayout());
         disableComponentsLaunchCluster();
         fsMenuJob.add(panelComboJobs);
         fsMenuJob.add(btCreateJob);
         fsMenuJob.add(btDeleteJob);
         fsMenuJob.add(btRunStopJob);
         fsMenuJob.add(btCheckJob);
         fsMenuJob.add(btShowFiles);
         fsMenuHost.setLayout(new VerticalLayout());
         fsMenuHost.add(btViewHost);
         fsMenu.add(fsMenuJob);
         fsMenu.add(fsMenuHost);

         panelBody.setLayout(new ColumnLayout());
         panelBody.setPaddings(10,0,0,10);
        
         fsJob.add(panelJob);

         firstColumn=new Panel();
         secondColumn=new Panel();
        
         firstColumn.add(fsMenu, new AnchorLayoutData("85%"));
         secondColumn.add(fsJob, new AnchorLayoutData("85%"));
         
         panelBody.add(firstColumn,new ColumnLayoutData(0.19));
         panelBody.add(secondColumn,new ColumnLayoutData(0.81));
         panelTabRun.add(fsRunCluster);
         panelTabRun.add(panelBody);
    }
  
    private void initForm(FormPanel formulario)
    {
         formulario.setFrame(true);
         formulario.setLabelWidth(75);
         formulario.setBorder(false);
         formulario.setPaddings(5, 5, 5, 0);
         formulario.setLabelAlign(Position.TOP);
         formulario.setFileUpload(true);
         formulario.setWidth("50%");
         
         
    }
    private void initComboBox(ComboBox combo,Store options,String id,String label,String emptyText,String loading,String value)
    {
        combo.setForceSelection(true);
        combo.setMinChars(1);
        combo.setId(id);
        combo.setFieldLabel(label);
        if(options!=null)
        {
            combo.setStore(options);
            combo.setDisplayField("types");
        }
        combo.setMode(ComboBox.LOCAL);
        combo.setTriggerAction(ComboBox.ALL);
        combo.setEmptyText(emptyText);
        combo.setLoadingText(loading);
        combo.setTypeAhead(true);
        combo.setAllowBlank(false);
        combo.setSelectOnFocus(true);
        combo.setWidth(200);
        combo.setHideTrigger(false);
        if(!value.equals(""))
        combo.setValue(value);
    }
    private void initTabConfig(Panel panelTab,String title,String color)
    {
         panelTab.setTitle(title);
         panelTab.setLayout(new FormLayout());
         panelTab.setAutoHeight(true);
         panelTab.setBorder(false);
         panelTab.setPaddings(10);
         panelTab.setBodyStyle("background-color:"+color);
    }
    private void disableComponentsLaunchCluster()
    {
        btCreateJob.disable();
        btShowFiles.disable();
        btViewHost.disable();
        btRunStopJob.disable();
        btCheckJob.disable();
        btEnterCommand.disable();
        btDeleteJob.disable();
        txtCommands.disable();
        cbJobs.disable();
    }
    private Store createStore(ArrayList<String> namesJobs)
    {
            String matrix[][]=new String[namesJobs.size()][1];
            for(int i=0;i<namesJobs.size();i++)
                matrix[i][0]=new String((namesJobs.get(i)));
            Store storeNames = new SimpleStore(new String[]{"types"},  matrix);
            return storeNames;
    }
    private Store createStoreInit()
    {
            String matrix[][]=new String[0][0];
            Store storeNames = new SimpleStore(new String[]{"types"},  matrix);
            return storeNames;
    }
      private Store comboBoxNumber(int limit)
    {
            String matrixNumber[][]=new String[limit][1];
            for(int i=0;i<limit;i++)
                matrixNumber[i][0]=new String((i+1)+"");
             Store storeNumber = new SimpleStore(new String[]{"types"},  matrixNumber);
             return storeNumber;
    }
       private Object[][] getCompanyData() {
           return new Object[0][0];
//         return new Object[][]{
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "<a href='/static/blabla/some_resource.do'>link</a>"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"},
//                 new Object[]{"3m Co", new Double(71.72), "Details",
//                         "Manufacturing"}
//         };
     }
     private void setFieldConfiguration(Map config)
     {
        keyName.setValue((String)config.get("keyName"));
        clusterSize.setValue((String)config.get("cbSizeTotal"));
        clusterShell.setValue((String)config.get("cbShell"));
        clusterZone.setValue((String)config.get("cbZone")) ;
        if(config.get("ebsVolumeId")!=null)
        {
            ebsVolumeId.setValue((String)config.get("ebsVolumeId"));
            ebsDevice.setValue((String)config.get("ebsDevice"));
            ebsPartition.setValue((String)config.get("ebsPartition"));
            ebsMountPath.setValue((String)config.get("ebsMountPath"));
        }
        accountNumber.setValue((String)config.get("accountNumber"));
        awsKey.setValue((String)config.get("awsKey"));
        secretAws.setValue((String)config.get("secretAws"));

     }
     private Object[][] createStoreGridJobFiles(ArrayList files)
     {
         Object matrix[][]=new Object[files.size()][3];
            for(int i=0;i<files.size();i++)
            {
                Map file=(Map)files.get(i);
                matrix[i][0]=(String)file.get("nameFile");
                matrix[i][1]=(String)file.get("sizeFile");
                matrix[i][2]=(String)file.get("linkFile");
            }           
            return matrix;
     }
}
